import {
  getUserInfoApi,
  loginApi,
  getProfileApi,
  editProfileApi,
  updatePhotoApi,
} from "@/apis/user";
import { RootState, RootThunkAction } from "@/types/store";
import { getToken, setToken, clearToken } from "@/utils/storage";
import {
  Action,
  createSlice,
  ThunkDispatch,
} from "@reduxjs/toolkit";

// 初始用户信息
const initUserInfo = {
  id: "",
  name: "",
  photo: "",
  art_count: 0,
  follow_count: 0,
  fans_count: 0,
  like_count: 0,
};

const userSlice = createSlice({
  name: "user",
  initialState: {
    token: getToken(),
    userInfo: { ...initUserInfo },
    profile: {
      id: "",
      name: "",
      photo: "",
      mobile: "",
      gender: "",
      birthday: "",
      intro: "",
    },
  },
  reducers: {
    setTokenState: (state, action) => {
      state.token = action.payload;
      setToken(action.payload);
    },
    clearUserInfo: (state) => {
      state.token = {
        token: "",
        refresh_token: "",
      };
      state.userInfo = { ...initUserInfo };
      clearToken();
    },
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
    },
    setProfile: (state, action) => {
      state.profile = { ...state.profile, ...action.payload };
    },
  },
});

export const { setTokenState, clearUserInfo, setUserInfo, setProfile } =
  userSlice.actions;

// 登录
export const fetchLogin =
  (loginData: LoginParams): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    const { data } = await loginApi(loginData);
    dispatch(setTokenState(data.data));
  };

// 获取用户信息
export const fetchUserInfo =
  (): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    const { data } = await getUserInfoApi();
    dispatch(setUserInfo(data.data));
  };

// 获取用户资料
export const fetchProfile =
  (): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    const { data } = await getProfileApi();
    dispatch(setProfile(data.data));
  };

// 编辑用户资料
export const fetchEditProfile =
  (profileData: Partial<Profile>): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    await editProfileApi(profileData);
    dispatch(setProfile(profileData));
  };

// 更新用户头像
export const fetchUpdatePhoto =
  (file: FormData): RootThunkAction =>
  async (dispatch: ThunkDispatch<RootState, unknown, Action<string>>) => {
    const { data } = await updatePhotoApi(file);
    dispatch(setProfile({ photo: data.data.photo }));
  };

export default userSlice.reducer;
